/**
 * Created by Kpeng on 2017/7/3.
 * Depending on the jquery-1.12.4.min.js.
 * Depending on the common.js.
 * Depending on the style.min.css.
 * To cite this document, always state the source as shown above.
 * -------------------------------
 * Module:申领合同
 * -------------------------------
 */
$(function () {
  // wzERP.Contract.init();
  // wzERP.Contract.turnPage();//分页
  wzERP.Common.inlineDate('#date1', '#date2');  //联动日期
  //验证规则
  var file = {}
  file.checkform = function (ele) {
    /*Arg Guide
     @ ele 要验证的表单
     */
    $(ele).form('submit');
    return $(ele).hasClass('error');
  }
  file.verifier = function (_selector) {
    /*Arg Guide
     @_selector: 对象选择器
     */
    $(_selector).form({
      on: 'blur',
      transition: 'fade',
      fields: {
        //客户名称
        customerName: {
          identifier: 'contract',
          rules: [{
            type: 'empty',
            prompt: '请输入客户名称'
          }]
        },
        //联系电话
        contactNumber: {
          identifier: 'contactNumber',
          rules: [{
            type: 'empty',
            prompt: '请输入联系电话'
          },
            {
              type: 'regExp[/^[0-9-]{0,20}$/]',
              prompt: '只能输入数字及-，字数限制20字'
            }]
        }
      }
    });

  };
  file.verifier('.file-verifier');//开启验证功能

  template.defaults.imports.dateTimes = function (now) {
    if (now == null) {
      return ''
    }
    function add0(m) {
      return m < 10 ? '0' + m : m
    }

    var time = new Date(now);
    var y = time.getFullYear();
    var m = time.getMonth() + 1;
    var d = time.getDate();
    var h = time.getHours();
    var mm = time.getMinutes();
    var s = time.getSeconds();
    return y + '-' + add0(m) + '-' + add0(d) + ' ' + add0(h) + ':' + add0(mm)
        + ':' + add0(s);
  }
  //获取时间和内容方法和当前页，每页显示条数
  function timeS() {
    var timeA = {}
    // 获取表单时间
    var content = $("#searchForm").serialize()
    //使用方法分割取出
    var contentS = content.split('&')
    var obj = {}
    for (var i = 0; i < contentS.length; i++) {
      var con = contentS[i].toString()
      var son = con.split('=')
      obj[son[0]] = son[1]
    }
    //获取当前每页应该显示条数
    timeA.num = $('#numberOf select').val()
    //获取搜索框内容
    timeA.searchKey = $('#searchKeyA').val()
    //获取分割好的起止时间
    timeA.startDate = obj.startDate
    timeA.endDate = obj.endDate
    //当前页
    timeA.page = $('.layui-laypage-skip').val()
    return timeA
  }

//表单模板数据请求
  demo(1)
// 获取当前页面内容
  function demo(curr, num, searchKey, startDate, endDate) {
    //curr:当前页
    //num:每页显示条数
    //searchKey:搜索内容
    //startDate:开始时间
    //endDate:结束时间
    $.get('/order/contract/queryByPage', {
      current: curr || 1,
      pageSize: num || 10,
      searchKey: searchKey,
      startDate: startDate,
      endDate: endDate
    }, function (content) {
      if (content.code == 9999) {
        // debugger
        layer.msg(content.msg, {time: 1000});
        wzERP.Common.TimeoutLogin();
        return false;
      }
      //获取内容显示到模板上
      $('#formData').html(template('formTpl', content.data))
      $('.recordOne').text(content.data.total)
      $('.recordTwo').text(content.data.pages)
      console.log(content.data)
      permissonHandler();
      // 分页
      layui.use(['laypage', 'layer'], function () {
        var laypage = layui.laypage;
        laypage({
          cont: 'turn-page',
          curr: curr || 1,
          pages: content.data.pages,
          skin: '#457fe6',
          skip: true,
          jump: function (obj, first) {
            var timeA = timeS()
            if (!first) {
              demo(obj.curr, timeA.num, timeA.searchKey, timeA.startDate,
                  timeA.endDate);
            }
          }
        });
      });
    })
  }

// 每页显示条数
  $('#numberOf').on('click', function () {
    //获取当前页数
    var page = $('.layui-laypage-skip').val()
    // 获取表单时间
    var content = $("#searchForm").serialize()
    //使用方法分割取出
    var contentS = content.split('&')
    var obj = {}
    for (var i = 0; i < contentS.length; i++) {
      var con = contentS[i].toString()
      var son = con.split('=')
      obj[son[0]] = son[1]
    }
    //获取当前每页应该显示条数
    var num = $('#numberOf select').val()
    //获取搜索框内容
    var searchKey = $('#searchKeyA').val()
    //获取分割好的起止时间
    var startDate = obj.startDate
    var endDate = obj.endDate
    demo(page, num, searchKey, startDate, endDate)
  })
//合同提交
  $('.contractAddType').on('click', function () {
    $('#modal').modal({
      closable: false,
      transition: 'fade'
    }).modal('show')
    $('#addContractForm .text').text('请选择类型')
  })
  $('#Submission').on('click', function () {
    //判断内容是否输入
    if (file.checkform('#addContractForm')) {
      return false
    }
    // 表单ajax请求
    if ($('#addContractForm .text').text() == '请选择类型') {
      layer.msg('请选择合同类型', {icon: 5})
      return false
    }
    var contractType = $('.contractTypeA').val()
    var remark = $('.remark').val()
    var customerName = $('#contract').val()
    $('#addContractForm').ajaxSubmit({
      data: {
        contractType: contractType,
        remark: remark,
        customerName: customerName
      },
      //成功后的回调函数
      success: function (data) {
        // 判断请求是否成功
        if (data.code == 0) {
          // 提示弹窗
          layer.msg('提交成功', {icon: 7})
          //关闭模态框
          $('#modal').modal('hide')
          var timeA = timeS()
          demo(timeA.page, timeA.num, timeA.searchKey, timeA.startDate,
              timeA.endDate)
        }
        else if (data.code == 9999) {
          // debugger
          layer.msg(data.msg, {time: 1000});
          wzERP.Common.TimeoutLogin();
          return false;
        }
      },
      // 请求成功以后清除表单的内容
      clearForm: true
    })
  })
  //获取时间和内容方法和当前页，每页显示条数
  function timeS() {
    var timeA = {}
    // 获取表单时间
    var content = $("#searchForm").serialize()
    //使用方法分割取出
    var contentS = content.split('&')
    var obj = {}
    for (var i = 0; i < contentS.length; i++) {
      var con = contentS[i].toString()
      var son = con.split('=')
      obj[son[0]] = son[1]
    }
    //获取当前每页应该显示条数
    timeA.num = $('#numberOf select').val()
    //获取搜索框内容
    timeA.searchKey = $('#searchKeyA').val()
    //获取分割好的起止时间
    timeA.startDate = obj.startDate
    timeA.endDate = obj.endDate
    //当前页
    timeA.page = $('.layui-laypage-skip').val()
    return timeA
  }

//查询业务
  $("#timeA").on('click', function () {
    // 获取表单时间
    var content = $("#searchForm").serialize()
    //使用方法分割取出
    var contentS = content.split('&')
    var obj = {}
    for (var i = 0; i < contentS.length; i++) {
      var con = contentS[i].toString()
      var son = con.split('=')
      obj[son[0]] = son[1]
    }
    //获取当前每页应该显示条数
    var num = $('#numberOf select').val()
    //获取搜索框内容
    var searchKey = $('#searchKeyA').val()
    //获取分割好的起止时间
    var startDate = obj.startDate
    var endDate = obj.endDate
    //获取搜索内容
    query(1, num, searchKey, startDate, endDate)
    function query(curr, num, searchKey, startDate, endDate) {
      $.get('/order/contract/queryByPage', {
        current: curr || 1,
        pageSize: num || 10,
        searchKey: searchKey,
        startDate: startDate,
        endDate: endDate
      }, function (content) {
        if (content.code == 9999) {
          // debugger
          layer.msg(content.msg, {time: 1000});
          wzERP.Common.TimeoutLogin();
          return false;
        }
        //获取内容显示到模板上
        $('#formData').html(template('formTpl', content.data))
        $('.recordOne').text(content.data.total)
        $('.recordTwo').text(content.data.pages)
        // 分页
        layui.use(['laypage', 'layer'], function () {
          var laypage = layui.laypage;
          laypage({
            cont: 'turn-page',
            curr: curr || 1,
            pages: content.data.pages,
            skin: '#457fe6',
            skip: true,
            jump: function (obj, first) {
              var num = $('#numberOf select').val()
              if (!first) {
                query(obj.curr, num, searchKey, startDate, endDate);
              }
            }
          });
        });
      })
    }

    return false
  })

//删除业务
  $('#formData').on('click', '.delA', function () {
    //模态框显示方法
    /*$('#delAS').modal('show')
     // 删除页面的订单号
     $('#textA').text($(this).attr('data-num'))
     // 获取ID
     var numR = $(this).attr('data-id')
     $('#delH').attr('data-id',numR)*/

    var id = $(this).data('id');
    layer.alert('确定删除该合同吗？', {
          title: '提示信息',
          btn: ['取消', '确认'],
          btn1: function (index) {
            layer.close(index)
          },
          btn2: function () {
            $.post('/order/contract/delete', {id: id}, function (data) {
              if (data.code == 0) {
                layer.msg('删除成功', {icon: 3})
                var timeA = timeS()
                demo(timeA.page, timeA.num, timeA.searchKey, timeA.startDate,
                    timeA.endDate)
              }
              else if (data.code == 9999) {
                // debugger
                layer.msg(data.msg, {time: 1000});
                wzERP.Common.TimeoutLogin();
                return false;
              }
              else {
                layer.msg('删除失败', {icon: 3})
              }
            })
          }
        }
    );
  })

//详情业务
  $('#formData').on('click', '.details', function () {
    //模态框显示方法
    $('#modalA').modal({
      closable: false,
      transition: 'fade'
    }).modal('show')
    $.get('/order/contract/queryDetail', {id: $(this).attr('data-id')},
        function (content) {
          if (content.code == 9999) {
            layer.msg(content.msg, {time: 1000});
            wzERP.Common.TimeoutLogin();
            return false;
          }
          //获取内容显示到模板上
          $('#modalContentA').html(template('modalDetails', content))
        })
  })

//编辑合同
  $('#formData').on('click', '.editContract', function () {
    //模态框显示方法
    $('#editModal').modal({
      closable: false,
      transition: 'fade'
    }).modal('show')
    // 获取ID
    var id = $(this).attr('data-id')
    $.get('/order/contract/queryDetail', {id: id}, function (content) {
      if (content.code == 9999) {
        // debugger
        layer.msg(content.msg, {time: 1000});
        wzERP.Common.TimeoutLogin();
        return false;
      }
      //获取内容显示到模板上
      $('#editModal').html(template('contractTemplate', content))
      //更改下来框默认选项
      $('#contractTypeA').val(content.data.contractType)
      console.log(content)
    });
  })
  $('#editModal').on('click', '#editSubmission', function () {
    var remark = $('.remarkA').val()
    var id = $(this).attr('data-id')
    // 表单ajax请求
    $('#editSubForm').ajaxSubmit({
      url: '/order/contract/addOrUpdate',
      type: 'post',
      data: {id: id, remark: remark},
      //成功后的回调函数
      success: function (data) {
        // 判断请求是否成功
        if (data.code == 0) {
          // 提示弹窗
          layer.msg('提交成功', {icon: 3})
          //请求成功以后关闭弹窗
          // $('#modal').parent().modal('show')
          var timeA = timeS()
          demo(timeA.page, timeA.num, timeA.searchKey, timeA.startDate,
              timeA.endDate)
        }
        else if (data.code == 9999) {
          // debugger
          layer.msg(data.msg, {time: 1000});
          wzERP.Common.TimeoutLogin();
          return false;
        }
      },
      // 请求成功以后清除表单的内容
      clearForm: true
    })
  })

//审核合同
  $('#formData').on('click', '.auditCon', function () {
    $('#auditContract').modal({
      closable: false,
      transition: 'fade'
    }).modal('show')
    $.get('/order/contract/queryDetail', {id: $(this).attr('data-id')},
        function (content) {
          if (content.code == 9999) {
            layer.msg(content.msg, {time: 1000});
            wzERP.Common.TimeoutLogin();
            return false;
          }
          $('#auditContract').html(template('auditTemplate', content))

        })
  })
  $('#auditContract').on('click', '#auditSubmission', function () {
    //检查是否有审核选项
    if ($('.auditStatus').val() == '') {
      layer.msg('请选择审核结果', {icon: 5})
      return false
    }
    //审核不通过时，检查是否填写内容
    if ($('.auditStatus').val() == 2) {
      if ($('#reviewRemarks').val() == '') {
        layer.msg('请在备注中说明不通过原因！', {icon: 5})
        return false
      }
    }
    var id = $(this).attr('data-id')
    $('#auditContractForm').ajaxSubmit({
      data: {id: id},
      //成功后的回调函数
      success: function (data) {
        // 判断请求是否成功
        if (data.code == 0) {
          // 提示弹窗
          layer.msg('提交成功', {icon: 7})
          $('#auditContract').modal('hide')
          var timeA = timeS()
          demo(timeA.page, timeA.num, timeA.searchKey, timeA.startDate,
              timeA.endDate)
        }
        else if (data.code == 9999) {
          // debugger
          layer.msg(data.msg, {time: 1000});
          wzERP.Common.TimeoutLogin();
          return false;
        }
        else {
          // 提示弹窗
          layer.msg('提交失败', {icon: 5})
        }
      },
      // 请求成功以后清除表单的内容
      clearForm: true
    })
  })

});




